package io.gitee.lwq.encrypt.spring.boot.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.json.JSONUtil;
import io.gitee.lwq.encrypt.spring.boot.common.encrypt.strategy.impl.RsaSignAndAesEncryptStrategyImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @description:
 * @author: lwq
 */
public class RsaSignAndAesEncryptClientUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(RsaSignAndAesEncryptClientUtil.class);
    public static void main(String[] args) {
        RsaSignAndAesEncryptStrategyImpl strategyImpl2=new RsaSignAndAesEncryptStrategyImpl();
       String appContent="{\n" +
               "  \n" +
               "  \"size\": 0,\n" +
               "  \"model\": {\n" +
               "    \"companyName\": \"lwq\",\n" +
               "    \"memberName\": \"lwq0526\"\n" +
               "  },\n" +
               "  \"page\": 0,\n" +
               "  \"conditions\": [\n" +
               "  \n" +
               "  ]\n" +
               "}";

//       buildAppSendParam(appContent);

        String serviceBody="{\n" +
                "    \"encryptContent\": \"qecy7zEPm6sW6GS9JBFneBxWG41LlCJwcRISH7jikQ2nRVfS/xiy3o5myZpoeMUIOQiBQ+Uqtl/iPdCMRRjkq3Uuwbw1SlCUiZaTIl0RKZNiUqHyvvRAbFVMgcskhiShWsEaRhAC13ovoFCxtAOdIO/7ShPTylP9Tc3FrdLKYZIrpjSeU6xLKJynEqj/utGR2qjvZqwn2lbEFuLbJPqI8w==\",\n" +
                "    \"sign\": \"Zio8mxpxim/JOkIbCinof5uKVLi7S8+kXDeqJAvHYO4Jk1f7Yn2E31xehSxTLZI7cmLydV/jsBJibmhTavRvgiNSgmqNtbNdiak9uxbPXvYr4qvx3gFTNUthNmNYvrHeJ9sHYjDWqgjMdk4axCI1+m3RZOhdi9FIALNaZjBih5iWH36q+d0zhhesPEfLphBAg13B8nBgDqeeSGqqJsIz/S9T9F4/UfFOto/HONFBS7GLszgysSrRrlBfXD9G+HX6mgKu62Al+Ho5bGkETyGeC2sAO3PGl6Sm+lDsNN6h1V3AAOkAA2xZGV0jEhD3ntChiji8H9O1t0xsToMzoQLLqQ==\",\n" +
                "    \"serviceKey\": \"serviceKey\",\n" +
                "    \"version\": \"v1\",\n" +
                "    \"encryptSecret\": \"bMTh67WizI9SmuTbhFlGbjvpLgOPoppVnLTiuQYXchNNbWxqTkyXMxDfFrXCZTXEELSs6Jrs5EcdIonq5WbXJg/mzuA5kmOPVJPZsY2wBbARr78qa6TWJeH6s7E8L9SZyYwC/YPYV0H0cylCwNe97F5FnSPGa40Jpz4mEEF8wsk=\",\n" +
                "    \"timestamp\": 1748502156250\n" +
                "}";
        decryptServiceBody(JSONUtil.toBean(serviceBody, Map.class));
    }

    public static Map<String, Object> buildAppSendParam(String appContent) {
        String appKey = "appKey";
        Long timestamp = System.currentTimeMillis();
        String version = "v1";

        byte[] keyBytes = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(), 256).getEncoded();
        String appAppSecret= Base64.encode(keyBytes);

        String encryptSecret =getServiceRsa().encryptBase64(appAppSecret,KeyType.PublicKey);
        Map<String, Object> param=new HashMap<>();
        String sha256DecryptContent = SecureUtil.sha256(appContent);

        String encryptContent=SecureUtil.aes(Base64.decode(appAppSecret))
                .encryptBase64(appContent);


        String signStr = StrUtil.format("{}-{}-{}-{}-{}",appKey,timestamp,version,appAppSecret,sha256DecryptContent);
        LOGGER.info("buildAppSendParam signStr:{}",signStr);
        String sign = getClientRsa().encryptBase64(signStr,KeyType.PrivateKey);
        param.put("appKey",appKey);
        param.put("timestamp",timestamp);
        param.put("version",version);
        param.put("encryptSecret",encryptSecret);
        param.put("encryptContent",encryptContent);
        param.put("sign",sign);
        LOGGER.info("buildAppSendParam param:{}",JSONUtil.toJsonStr(param) );
        return param;
    }
    public static String decryptServiceBody(Map<String, Object> appSendParam) {
        String serviceKey = (String) appSendParam.get("serviceKey");
        Long timestamp = (Long) appSendParam.get("timestamp");
        String version = (String)appSendParam.get("version");
        String encryptSecret = (String)appSendParam.get("encryptSecret");
        String encryptContent =(String) appSendParam.get("encryptContent");
        String sign = (String)appSendParam.get("sign");

        LOGGER.info("decryptServiceBody appSendParam:{}",appSendParam.toString());

        String appAppSecret=getClientRsa().decryptStr(encryptSecret, KeyType.PrivateKey);
        String appContent= SecureUtil.aes(Base64.decode(appAppSecret))
                .decryptStr(encryptContent);
        String sha256DecryptContent = SecureUtil.sha256(appContent);
        String signStr = StrUtil.format("{}-{}-{}-{}-{}",serviceKey,timestamp,version,appAppSecret,sha256DecryptContent);
        String decryptSign = getServiceRsa().decryptStr(sign,KeyType.PublicKey);
        if(!Objects.equals(signStr,decryptSign)){
            LOGGER.info("signStr:{},decryptSign:{}",signStr,decryptSign);
            throw new RuntimeException("解密失败");
        }
        LOGGER.info(appContent);
        return appContent;
    }
    public static RSA getClientRsa(){
        String privateKey="MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAN468DKwfiH75935bLXrJnRtLuZEsY+lPUtZJWVvCRuAcfdMPp0caaABht2KKtLBM6Uypz4KDTxSjMWUBxWR0RfguT9McdWRBUDc7ib0kKiFeMWRT07PkwF43TfF/eqFingb8/VzpVzKgJkDmWbyGsCzh1IYVjRlyYqUW6LnIfW9AgMBAAECgYAkldzl5274fs1zGoVGZMZhq/jo4V2/CYPQBAbXTmKYM7rvbM6xFFSiSiYPElhO9o4fT/m/Ca4YpHl27JIG/8jFgElg9EmmDZCKC5Ozr9t4agckHFatoZrE7z46wP67/6PvF0Cl5YKFFQx78h5VT3UDMHn48ba86jp9C22LSr+iyQJBAO4xHdaaPMRqkmz5JBzgn9iEAd2KQgnlNFifuzV4NuO+4Vtt/J6GE2SAMuyWSWaxuXiTJXQeTlbZCRRzocje+okCQQDu2FLGC0RTLW6pVfLg6fCdu9VZk0hVOcMKoe+vJgoJvAGjorVLfOmcEAwN29GXq2z5Knz0PAMmGwZQt2lZ8ASVAkAvzOuQBaPsRvbbp6P3p5xsdxFoxDY8hiLbJjMLp/RcABJ5prjrlzyNDq0pjX9tfH0cFWuOwgY2p5eK4ym0hgsBAkAEvcye29hmYk+BExC4QEyjhPgOSCs2begeTOqqKnImkVHjArbgocEtdPAYUlXN0fxe0eYbHxnc5spwTcPMokQlAkEAvstA6jILHr9U+N/dj5BeKdIgnTMIUGsCqy5OZsn3zRom5McRCmDJvZL2mUUYA/2rt3Kgo/ugs6/T9H7r34j96w==";
        String publicKey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDeOvAysH4h++fd+Wy16yZ0bS7mRLGPpT1LWSVlbwkbgHH3TD6dHGmgAYbdiirSwTOlMqc+Cg08UozFlAcVkdEX4Lk/THHVkQVA3O4m9JCohXjFkU9Oz5MBeN03xf3qhYp4G/P1c6VcyoCZA5lm8hrAs4dSGFY0ZcmKlFui5yH1vQIDAQAB";
        return SecureUtil.rsa(Base64.decode(privateKey),Base64.decode(publicKey));
    }
    public static RSA getServiceRsa(){
        String publicKey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCWiPwSinvui9mU6P2e1UWQpB8G88sweyUHB3XlHQAaReFq/rW52+zt62NlTdKa+JWID7NG++i3cCG1Y/o1Fzsje6iOiUAbWLXuhcFP+xBqJoDMnovZuCFpJC3H9dATYhuaa0wtmOZ5OlZJQVlWr7Hg44veCzfbsjvJaTtOgS7AsQIDAQAB";
        return SecureUtil.rsa(null,Base64.decode(publicKey));
    }
}
